package com.example.springboottools.gms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class SimpleDateFormatSerializerImpl implements ObjectSerializer {
    private final String pattern;

    public SimpleDateFormatSerializerImpl(String pattern){
        this.pattern = pattern;
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object == null) {
            serializer.out.writeNull();
            return;
        }

        Date date = (Date) object;
        Locale locale = new Locale("en", "US");
        TimeZone timeZone    = JSON.defaultTimeZone;
        SimpleDateFormat format = new SimpleDateFormat(pattern, locale);
        format.setTimeZone(timeZone);

        String text = format.format(date);
        serializer.write(text);
    }
}
